/**
 * 
 */
package com.eis.persist.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;

import com.eis.exception.EisErrorCode;
import com.eis.exception.EisSysException;
import com.eis.persist.dao.BizSystemDAO;
import com.eis.persist.dao.base.BaseDAO;
import com.eis.persist.dao.util.Constants;
import com.eis.persist.model.bizsystem.PersistBizSystem;
import com.eis.persist.model.bizsystem.PersistConnectorConfigure;

/**
 * @author wei
 *
 */
public class BizSystemDAOImpl extends BaseDAO implements BizSystemDAO {

	public BizSystemDAOImpl(JdbcTemplate dataSource, String currentUserName) {
		super(dataSource, currentUserName);
	}
	
	public BizSystemDAOImpl(JdbcTemplate dataSource) {
		super(dataSource);
	}

	/* (non-Javadoc)
	 * @see com.eis.persist.dao.BizSystemDAO#getAllBizSystems()
	 */
	@Override
	public List<PersistBizSystem> getAllBizSystems() {
		String sql = "select * from tb_biz_system";
		
		List<Map<String, Object>> results 
			= dataSource.queryForList(sql);
		
		List<PersistBizSystem> resultList = new ArrayList<PersistBizSystem>();
		for (Map<String, Object> oneResult : results) {
			PersistBizSystem bizSystem = new PersistBizSystem(oneResult);
			resultList.add(bizSystem);
		}
		
		return resultList;
	}

	/* (non-Javadoc)
	 * @see com.eis.persist.dao.BizSystemDAO#getConnectorConfig(int)
	 */
	@Override
	public List<PersistConnectorConfigure> getConnectorConfigs(int bizSystemId) {
		String sql = "select * from tb_connector_config where bizsysId=?";
		
		List<Map<String, Object>> results 
			= dataSource.queryForList(sql, bizSystemId);
		
		List<PersistConnectorConfigure> resultList = new ArrayList<PersistConnectorConfigure>();
		for (Map<String, Object> oneResult : results) {
			PersistConnectorConfigure config = new PersistConnectorConfigure(oneResult);
			resultList.add(config);
		}
		
		return resultList;
	}

	/* (non-Javadoc)
	 * @see com.eis.persist.dao.BizSystemDAO#saveBizSystem(com.eis.persist.model.bizsystem.PersistBizSystem)
	 */
	@Override
	public boolean saveBizSystem(PersistBizSystem bizSystem) throws EisSysException {
		int result = 0;
		if (bizSystem.getId() > 0) {
			super.preUpdate(bizSystem);
			// look for the exist business system
			String getByIdSql = "select count(id) from tb_biz_system where id=?";
			int idCount 
				= dataSource.queryForInt(getByIdSql, bizSystem.getId());
			if (idCount > 0) {
				// check if the name field is duplicate
				String getByNameSql = "select count(id) from tb_biz_system where name like ? and id<>?";
				int nameCount
					= dataSource.queryForInt(getByNameSql, bizSystem.getName(), bizSystem.getId());
				if (nameCount > 0) {
					throw new EisSysException(EisErrorCode.BizSystemExistForUpdate);
				} else {
					// update it
					String updateSql = "update tb_biz_system set " +
							"name=?," +
							"connectorStaticsClassName=?," +
							"updateDate=?, " +
							"updatedBy=? " +
							"where " +
							"id=?";
					result =  dataSource.update(
							updateSql,
							bizSystem.getName(), 
							bizSystem.getConnectorStaticsClassName(), 
							bizSystem.getUpdateDate(),
							bizSystem.getUpdatedBy(),
							bizSystem.getId());
				}
				
				
			} else {
				throw new EisSysException(EisErrorCode.BizSystemNotExistForUpdate);
			}
		} else {
			super.preInsert(bizSystem);
			// check if the name field is duplicate
			String getByNameSql = "select count(id) from tb_biz_system where name like ?";
			
			int count = dataSource.queryForInt(getByNameSql, bizSystem.getName());
			if (count > 0) {
				throw new EisSysException(EisErrorCode.BizSystemExistForInsert);
			} else {
				// save it
				String insertSql = "insert into tb_biz_system(" +
						"name,connectorStaticsClassName,createBy,createDate" +
						") values(" +
						"?,?,?,?" +
						")";
				result =  dataSource.update(
						insertSql,
						bizSystem.getName(), 
						bizSystem.getConnectorStaticsClassName(), 
						bizSystem.getCreatedBy(),
						bizSystem.getCreateDate());
				
				// add default group
				String defaultGroupSql = "insert into tb_layoutgroup (defaultDisplayName,bizsysId,createBy,createDate) values " +
						"(?,(select id from tb_biz_system where name like ?),?,?)";
				result =  dataSource.update(
						defaultGroupSql,
						Constants.DEFAULT_GROUP_NAME, 
						bizSystem.getName(), 
						bizSystem.getCreatedBy(),
						bizSystem.getCreateDate());
			}
		}
		
		return result > 0;
	}

	/* (non-Javadoc)
	 * @see com.eis.persist.dao.BizSystemDAO#saveConnectorConfigure(com.eis.persist.model.bizsystem.PersistConnectorConfigure)
	 */
	@Override
	public boolean saveConnectorConfigure(
			PersistConnectorConfigure connectorConfigure) throws EisSysException {
		int result = 0;
		if (connectorConfigure.getId() > 0) {
			super.preUpdate(connectorConfigure);
			// look for the exist connector configure
			String getByIdSql = "select count(id) from tb_connector_config where id=?";
			int idCount 
				= dataSource.queryForInt(getByIdSql, connectorConfigure.getId());
			if (idCount > 0) {
				// update it
				String updateSql = "update tb_connector_config set "
						+ "name=?," + "bizsysId=?," + "configXml=? "
						+ "updateDate=? " + "updatedBy=? " + "where " + "id=?";
				result = dataSource.update(updateSql, connectorConfigure
						.getName(), connectorConfigure.getBizSystem().getId(),
						connectorConfigure.getConfigXml(), connectorConfigure
								.getUpdateDate(), connectorConfigure
								.getUpdatedBy());
			} else {
				throw new EisSysException(EisErrorCode.ConnectorConfigureNotExistForUpdate);
			}
		} else {
			super.preInsert(connectorConfigure);
			// save it
			String insertSql = "insert into tb_connector_config("
					+ "name,bizsysId,configXml,createBy,createDate"
					+ ") values(" + "?,?,?,?,?" + ")";
			result = dataSource.update(insertSql, connectorConfigure.getName(),
					connectorConfigure.getBizSystem().getId(),
					connectorConfigure.getConfigXml(),
					connectorConfigure.getCreatedBy(),
					connectorConfigure.getCreateDate());
		}
		
		return result > 0;
	}

	@Override
	public PersistBizSystem getBizSystem(int id) {
		String sql = "select * from tb_biz_system where id=?";
		
		List<Map<String, Object>> results = dataSource.queryForList(sql, id);
		
		if (results.size() > 0) {
			return new PersistBizSystem(results.get(0));
		} else {
			return null;
		}
	}

	@Override
	public PersistConnectorConfigure getConnectorConfig(int configId) {
		String getByIdSql = "select * from tb_connector_config where id=?";
		
		List<Map<String, Object>> results = dataSource.queryForList(getByIdSql, configId);
		
		if (results.size() > 0) {
			return new PersistConnectorConfigure(results.get(0));
		} else {
			return null;
		}
	}

	@Override
	public PersistConnectorConfigure getFunctionConfig(String functionId) {
		String sql = "select config.* from tb_connector_config config inner join tb_function func on func.bizsysConnectorConfig=config.id where func.functionId=?";
		
		List<Map<String, Object>> results = dataSource.queryForList(sql, functionId);
		if (results.size() > 0) {
			return new PersistConnectorConfigure(results.get(0));
		} else {
			return null;
		}
	}

	@Override
	public boolean deleteConnectorConfigure(int configId)
			throws EisSysException {
		int result = 0;
		if (configId > 0) {
			// look for the exist connector configure
			String getByIdSql = "select count(id) from tb_connector_config where id=?";
			int idCount 
				= dataSource.queryForInt(getByIdSql, configId);
			if (idCount > 0) {
				// update it
				String deleteSql = "delete from tb_connector_config where id=?";
				result = dataSource.update(deleteSql, configId);
			} else {
				throw new EisSysException(EisErrorCode.ConnectorConfigureNotExistForUpdate);
			}
		}
		
		return result > 0;
	}

}
